﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BYS.XiAnComDept.BussLogic;
using Microsoft.Win32;
using System.IO;
using System.Data;
using CsvHelper;
using System.Threading;
using System.Data.Entity;

namespace BYS.XiAnComDept.App.Pages
{
    /// <summary>
    /// Interaction logic for FundQuery.xaml
    /// </summary>
    public partial class FundQuery : UserControl
    {
        BllFactory bllFactory = new BllFactory();
        string[] commonColumnNames = null;

        public FundQuery()
        {
            InitializeComponent();
            this.commonColumnNames = this.DataGridFundData.Columns.Select(x => x.Header.ToString()).ToArray();
            this.ComboBoxYear.ItemsSource = UIHelper.GetAllYears().ConvertToDict(true);
            this.ComboBoxYear.SelectedIndex = 0;
            this.ComboBoxYear.DisplayMemberPath = "Value";
            this.InitFundTypeCheckboxList();
            this.ButtonExport.Visibility = Visibility.Hidden;
        }

        private void InitFundTypeCheckboxList()
        {
            using(BllFactory bllFactory = new BllFactory())
            {
                this.FundTypePanel.Children.Clear();
                List<FundType> fundTypes = bllFactory.FundTypeBll.GetAllFundTypes();
                foreach (FundType fundType in fundTypes)
                {
                    CheckBox checkBox = new CheckBox();
                    checkBox.Content = fundType.FundTypeName;
                    checkBox.Tag = fundType;
                    checkBox.Margin = new Thickness(0, 0, 20, 0);
                    this.FundTypePanel.Children.Add(checkBox);
                }
            }
        }

        public List<FundType> GetCheckedFundTypes()
        {
            List<FundType> fundTypes = new List<FundType>();
            UIElementCollection children = this.FundTypePanel.Children;
            foreach (UIElement element in children)
            {
                if (element is CheckBox)
                {
                    CheckBox checkBoxFundType = (element as CheckBox);
                    if (checkBoxFundType.IsChecked == true)
                    {
                        fundTypes.Add(checkBoxFundType.Tag as FundType);
                    }
                }
            }
            return fundTypes;
        }

        private void InitDataGridFund(IEnumerable<Fund> funds)
        {
            DataGridColumn[] colsNeedtoRemove = this.DataGridFundData.Columns.Where(x => !this.commonColumnNames.Contains(x.Header.ToString())).ToArray();
            foreach(DataGridColumn col in colsNeedtoRemove)
            {
                this.DataGridFundData.Columns.Remove(col);
            }
            int insertPosition = 3;
            // if all funds have save project field names we can show the project Fields as multi-columns
            if (bllFactory.ProjectFieldBll.IsHavingSaveProjectFieldNames(funds))
            {
                IEnumerable<string> projectFieldNames = bllFactory.ProjectFieldBll.GetProjectFieldNames(funds);
                foreach (string fieldName in projectFieldNames)
                {
                    DataGridColumn newCol = new DataGridTextColumn()
                    {
                        Header = fieldName,
                        Binding = new Binding(string.Format("[{0}]", fieldName)),
                    };
                    this.DataGridFundData.Columns.Insert(insertPosition++, newCol); 
                }
            }
            else
            {
                DataGridColumn colProjectInfo = new DataGridTextColumn()
                {
                    Header = "项目信息",
                    Binding = new Binding("ProjectInfo"),
                };
                this.DataGridFundData.Columns.Insert(insertPosition++, colProjectInfo); 
            }
        }

        private void ButtonSearch_Click(object sender, RoutedEventArgs e)
        {
            int year = ((KeyValuePair<int, string>)this.ComboBoxYear.SelectedItem).Key;
            using (BllFactory factory = new BllFactory())
            {
                List<Fund> fundData = factory.FundBll.QueryFunds(year,
                               this.TextBoxComName.Text,
                               this.GetCheckedFundTypes());
                this.InitDataGridFund(fundData);
                this.DataGridFundData.ItemsSource = fundData;
                this.ButtonExport.Visibility = fundData.Count > 0 ? Visibility.Visible : Visibility.Hidden;
            }
            Dispatcher.BeginInvoke(new Action(() => {
                foreach (DataGridColumn column in this.DataGridFundData.Columns)
                {
                    if (!this.commonColumnNames.Contains(column.Header.ToString()))
                    {
                        if (column.Width.DisplayValue > 300)
                        {
                            column.Width = 300;
                        } else if (column.Width.DisplayValue > 200)
                        {
                            column.Width = 200;
                        }
                    }
                }
            }), System.Windows.Threading.DispatcherPriority.Render);
        }

        private void ButtonExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV文件|*.csv";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.Title = "选择要导出的EXCEL文件的位置";
            if (saveFileDialog.ShowDialog() == true)
            {
                TextWriter textWriter = new StreamWriter(saveFileDialog.FileName, false,  Encoding.UTF8);
                CsvWriter writer = new CsvWriter(textWriter, new CsvHelper.Configuration.CsvConfiguration());
                foreach(DataGridColumn col in this.DataGridFundData.Columns)
                {
                    writer.WriteField(col.Header.ToString());
                }
                writer.NextRecord();

                for (int i = 0; i < this.DataGridFundData.Items.Count; i++)
                {
                    for (int j = 0; j < this.DataGridFundData.Columns.Count; j++)
                    {
                        writer.WriteField((this.DataGridFundData.GetCell(i, j).Content as TextBlock).Text);
                    }
                    writer.NextRecord();
                }

                textWriter.Flush();
                textWriter.Close();
            }
        }

        private void DataRow_DoubleClick(object sender, RoutedEventArgs e)
        {
            DataGridRow row = sender as DataGridRow;
            Fund fund = row.Item as Fund;
            NavigationCommands.GoToPage.Execute("/Pages/FundEdit.xaml?FundGuid=" + fund.FundGuid.ToString(),  this);
        }

        private void ButtonRefreshFundTypes_Click(object sender, RoutedEventArgs e)
        {
            this.InitFundTypeCheckboxList();
        }
    }
}
